import { _decorator, Component, instantiate, Node, Prefab } from 'cc';
import { UIHeader } from '../common/UIHeader';
import { TabLayout } from '../common/TabLayout';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { EventManager } from '../event/EventManager';
import { Task, TaskStatus, TaskType } from '../entity/Task';
import TaskApi from '../api/TaskApi';
const { ccclass, property } = _decorator;

@ccclass('TaskIndex')
export class TaskIndex extends Component {

    @property(UIHeader)
    uiHeader:UIHeader
    @property(TabLayout)
    tabLayout:TabLayout
    @property(Node)
    content:Node
    @property(Prefab)
    mainTask:Prefab
    @property(Prefab)
    dailyTask:Prefab
    @property(Prefab)
    otherTask:Prefab

    start() {
        this.uiHeader.setData('任务中心')
        EventManager.instance.on('任务中心close', this.onClose, this)

        this.tabLayout.setData(['主线任务','每日任务','循环任务'])
        EventManager.instance.on('主线任务', this.onMain, this)
        EventManager.instance.on('每日任务', this.onDaily, this)
        EventManager.instance.on('循环任务', this.onOther, this)
        
        EventManager.instance.on(EventManager.EventType.ReceiveTaskBonus, this.refreshRedDot, this)
        this.refreshRedDot()
        // 清空缓存的任务列表，重新调用接口，获取新的任务数据
        Task.allTaskList = []

        this.onMain()
    }

    onMain(){
        this.content.destroyAllChildren()
        let node = instantiate(this.mainTask)
        this.content.addChild(node)
    }

    onDaily(){
        this.content.destroyAllChildren()
        this.content.destroyAllChildren()
        let node = instantiate(this.dailyTask)
        this.content.addChild(node)
    }

    onOther(){
        this.content.destroyAllChildren()
        this.content.destroyAllChildren()
        let node = instantiate(this.otherTask)
        this.content.addChild(node)
    }

    onClose(){
        UIManager.instance.closeUI(PrefabEnum.TaskIndex)
    }

    async refreshRedDot(){
        this.tabLayout.setRedDot('主线任务', false)
        this.tabLayout.setRedDot('每日任务', false)
        this.tabLayout.setRedDot('循环任务', false)
        let list = await Task.getTaskListByType(TaskType.Main)
        for(let item of list){
            if(item.status == TaskStatus.Complete){
                this.tabLayout.setRedDot('主线任务', true)
                break
            }
        }

        list = await Task.getTaskListByType(TaskType.Daily)
        for(let item of list){
            if(item.status == TaskStatus.Complete){
                this.tabLayout.setRedDot('每日任务', true)
                break
            }
        }

        list = await Task.getTaskListByType(TaskType.Other)
        for(let item of list){
            if(item.status == TaskStatus.Complete){
                this.tabLayout.setRedDot('循环任务', true)
                break
            }
        }
    }
    
}


